{include file="layout/layui_header" /}

<!-- 主要内容 -->
<div class="main-content">
    <div class="page-header">
        <h1 class="page-title">操作日志</h1>
        <p class="page-subtitle">查看系统操作记录和安全日志</p>
    </div>

    <!-- 日志统计卡片 -->
    <div class="layui-row layui-col-space20">
        <div class="layui-col-md3 layui-col-sm6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="fas fa-file-alt" style="color: #10b981; margin-right: 8px;"></i>
                    今日日志
                </div>
                <div class="layui-card-body">
                    <h2 style="margin: 0; color: #10b981; font-size: 28px;" id="todayLogs">0</h2>
                    <p style="margin: 5px 0 0 0; color: #666; font-size: 12px;">条记录</p>
                </div>
            </div>
        </div>
        <div class="layui-col-md3 layui-col-sm6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="fas fa-user-shield" style="color: #3b82f6; margin-right: 8px;"></i>
                    登录日志
                </div>
                <div class="layui-card-body">
                    <h2 style="margin: 0; color: #3b82f6; font-size: 28px;" id="loginLogs">0</h2>
                    <p style="margin: 5px 0 0 0; color: #666; font-size: 12px;">登录次数</p>
                </div>
            </div>
        </div>
        <div class="layui-col-md3 layui-col-sm6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="fas fa-exclamation-triangle" style="color: #f59e0b; margin-right: 8px;"></i>
                    异常操作
                </div>
                <div class="layui-card-body">
                    <h2 style="margin: 0; color: #f59e0b; font-size: 28px;" id="errorLogs">0</h2>
                    <p style="margin: 5px 0 0 0; color: #666; font-size: 12px;">异常记录</p>
                </div>
            </div>
        </div>
        <div class="layui-col-md3 layui-col-sm6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="fas fa-database" style="color: #ef4444; margin-right: 8px;"></i>
                    日志总数
                </div>
                <div class="layui-card-body">
                    <h2 style="margin: 0; color: #ef4444; font-size: 28px;" id="totalLogs">0</h2>
                    <p style="margin: 5px 0 0 0; color: #666; font-size: 12px;">历史记录</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 日志管理表格 -->
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>操作日志</h3>
        </div>
        <div class="layui-card-body">
            <!-- 搜索和操作栏 -->
            <div class="layui-row layui-col-space15" style="margin-bottom: 15px;">
                <div class="layui-col-md4">
                    <div class="layui-input-group">
                        <input type="text" id="searchInput" placeholder="搜索用户名或操作内容" class="layui-input">
                        <div class="layui-input-split layui-input-suffix">
                            <button class="layui-btn layui-btn-primary" onclick="searchLogs()">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="layui-col-md8" style="text-align: right;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="exportLogs()">
                        <i class="fas fa-download"></i>
                        导出日志
                    </button>
                    <button type="button" class="layui-btn layui-btn-warm" onclick="clearOldLogs()">
                        <i class="fas fa-trash-alt"></i>
                        清理过期日志
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" onclick="refreshLogs()">
                        <i class="fas fa-sync"></i>
                        刷新
                    </button>
                </div>
            </div>

            <!-- 过滤器 -->
            <div class="layui-form" style="margin-bottom: 15px;">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-md2">
                        <select name="moduleFilter" lay-filter="moduleFilter">
                            <option value="">所有模块</option>
                            <option value="login">登录模块</option>
                            <option value="vehicle">车辆管理</option>
                            <option value="payment">缴费管理</option>

                            <option value="settings">系统设置</option>
                            <option value="blacklist">黑名单</option>
                        </select>
                    </div>
                    <div class="layui-col-md2">
                        <select name="actionFilter" lay-filter="actionFilter">
                            <option value="">所有操作</option>
                            <option value="create">新增</option>
                            <option value="update">修改</option>
                            <option value="delete">删除</option>
                            <option value="login">登录</option>
                            <option value="logout">登出</option>
                            <option value="view">查看</option>
                        </select>
                    </div>
                    <div class="layui-col-md2">
                        <select name="levelFilter" lay-filter="levelFilter">
                            <option value="">所有级别</option>
                            <option value="info">信息</option>
                            <option value="warning">警告</option>
                            <option value="error">错误</option>
                            <option value="debug">调试</option>
                        </select>
                    </div>
                    <div class="layui-col-md3">
                        <input type="text" name="dateRange" placeholder="选择时间范围" class="layui-input" id="dateRange">
                    </div>
                    <div class="layui-col-md3">
                        <input type="text" name="ipFilter" placeholder="IP地址过滤" class="layui-input">
                    </div>
                </div>
            </div>

            <!-- 日志表格 -->
            <table id="logsTable" lay-filter="logsTable"></table>
        </div>
    </div>
</div>

<!-- 操作按钮模板 -->
<script type="text/html" id="logActionBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail">详情</a>
</script>

<!-- 日志级别模板 -->
<script type="text/html" id="levelTpl">
    {{# if(d.level == 'info') { }}
        <span class="layui-badge layui-bg-blue">信息</span>
    {{# } else if(d.level == 'warning') { }}
        <span class="layui-badge layui-bg-orange">警告</span>
    {{# } else if(d.level == 'error') { }}
        <span class="layui-badge layui-bg-red">错误</span>
    {{# } else { }}
        <span class="layui-badge layui-bg-gray">调试</span>
    {{# } }}
</script>

<script src="/assets/common/layui.js"></script>
<script>
layui.use(['table', 'form', 'layer', 'laydate','jquery'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var $ = layui.jquery;
    // 渲染日期范围选择器
    laydate.render({
        elem: '#dateRange',
        type: 'datetime',
        range: true
    });
    
    // 渲染日志表格
    table.render({
        elem: '#logsTable',
        url: '/admin/settings/getLogsList',
        page: true,
        id: 'logsTable',
        height: 'full-320',
        initSort: {
            field: 'created_at',
            type: 'desc'
        },
        cols: [[
            {field: 'id', title: 'ID', width: 80, sort: true},
            {field: 'user_name', title: '操作用户', width: 120},
            {field: 'url', title: '模块'},
            {field: 'url_name', title: '操作类型', width: 100},
            {field: 'ip', title: 'IP地址', width: 130},
            {field: 'user_agent', title: '浏览器', width: 200, hide: true},
            {field: 'level', title: '日志级别', width: 100, templet: '#levelTpl'},
            {field: 'create_time', title: '操作时间', width: 160, sort: true, templet:function(d){
                return layui.util.toDateString(d.create_time + '000','yyyy-MM-dd HH:mm:ss');
            }},
            {title: '操作', width: 100, toolbar: '#logActionBar', fixed: 'right'}
        ]],
        done: function(res) {
            // 更新统计数据
            updateLogStats(res.data);
        }
    });
    
    // 监听表格工具条
    table.on('tool(logsTable)', function(obj){
        var data = obj.data;
        if(obj.event === 'detail'){
            showLogDetail(data);
        }
    });
    
    // 监听过滤器变化
    form.on('select(moduleFilter)', function(data){
        reloadTable();
    });
    
    form.on('select(actionFilter)', function(data){
        reloadTable();
    });
    
    form.on('select(levelFilter)', function(data){
        reloadTable();
    });
    
    // 搜索功能
    window.searchLogs = function() {
        reloadTable();
    };
    
    // 刷新功能
    window.refreshLogs = function() {
        layer.msg('正在刷新...', {icon: 16});
        table.reload('logsTable');
    };
    
    // 导出日志
    window.exportLogs = function() {
        layer.confirm('确定要导出当前筛选条件下的日志吗？', {
            icon: 3,
            title: '确认导出'
        }, function(index) {
            layer.msg('正在导出，请稍候...', {icon: 16});
            
            // 获取当前筛选条件
            var params = getCurrentFilters();
            
            // 创建下载链接
            var downloadUrl = '/admin/settings/logs/export?' + new URLSearchParams(params).toString();
            
            // 模拟下载
            setTimeout(function() {
                layer.msg('导出成功！', {icon: 1});
                // 实际项目中这里应该触发下载
                // window.open(downloadUrl);
                layer.close(index);
            }, 2000);
        });
    };
    
    // 清理过期日志
    window.clearOldLogs = function() {
        layer.open({
            type: 1,
            title: '清理过期日志',
            area: ['400px', '300px'],
            content: `
                <div style="padding: 20px;">
                    <form class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label">保留天数</label>
                            <div class="layui-input-block">
                                <input type="number" name="days" value="30" min="7" max="365" class="layui-input">
                                <div class="layui-form-mid layui-word-aux">天前的日志将被删除</div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button type="button" class="layui-btn" onclick="confirmClearLogs()">确认清理</button>
                                <button type="button" class="layui-btn layui-btn-primary" onclick="layer.closeAll()">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            `
        });
    };
    
    // 确认清理日志
    window.confirmClearLogs = function() {
        var days = document.querySelector('input[name="days"]').value;
        layer.confirm('确定要删除 ' + days + ' 天前的日志吗？此操作不可恢复！', {
            icon: 3,
            title: '确认清理'
        }, function(index) {
            layer.msg('正在清理日志...', {icon: 16});
            
            // 这里发送AJAX请求清理日志
            setTimeout(function() {
                layer.msg('清理完成！共清理了 ' + Math.floor(Math.random() * 1000) + ' 条日志', {icon: 1});
                table.reload('logsTable');
                layer.closeAll();
            }, 2000);
        });
    };
    
    // 显示日志详情
    function showLogDetail(data) {
        var content = `
            <div style="padding: 20px; line-height: 2;">
                <table class="layui-table" lay-size="sm">
                    <tr><td width="120"><strong>日志ID:</strong></td><td>${data.id}</td></tr>
                    <tr><td><strong>操作用户:</strong></td><td>${data.user_id}</td></tr>
                    <tr><td><strong>操作模块:</strong></td><td>${data.url}</td></tr>
                    <tr><td><strong>操作类型:</strong></td><td>${data.url_name}</td></tr>
                    <tr><td><strong>IP地址:</strong></td><td>${data.ip}</td></tr>
                    <tr><td><strong>日志级别:</strong></td><td>${data.level}</td></tr>
                    <tr><td><strong>操作时间:</strong></td><td>${data.create_time}</td></tr>
                </table>
            </div>
        `;
        
        layer.open({
            type: 1,
            title: '日志详情',
            area: ['800px', '600px'],
            content: content,
            btn: ['关闭'],
            yes: function(index) {
                layer.close(index);
            }
        });
    }
    
    // 重新加载表格
    function reloadTable() {
        var params = getCurrentFilters();
        
        table.reload('logsTable', {
            where: params
        });
    }
    
    // 获取当前筛选条件
    function getCurrentFilters() {
        var searchText = document.getElementById('searchInput').value;
        var formData = form.val('form');
        
        return {
            search: searchText,
            module: formData.moduleFilter,
            action: formData.actionFilter,
            level: formData.levelFilter,
            date_range: formData.dateRange,
            ip: formData.ipFilter
        };
    }
    
    // 更新统计数据
    function updateLogStats(data) {
        var today = new Date().toDateString();
        var todayCount = data.filter(item => {
            var itemDate = new Date(item.created_at).toDateString();
            return itemDate === today;
        }).length;
        
        var loginCount = data.filter(item => item.action === 'login' || item.action === 'logout').length;
        var errorCount = data.filter(item => item.level === 'error').length;
        var totalCount = data.length;
        
        document.getElementById('todayLogs').textContent = todayCount;
        document.getElementById('loginLogs').textContent = loginCount;
        document.getElementById('errorLogs').textContent = errorCount;
        document.getElementById('totalLogs').textContent = totalCount;
    }
    
    // 从API获取并更新统计数据
    function updateStatsFromAPI() {
        $.get('/admin/settings/todayStats', function(res) {
            if (res.code === 0) {
                var stats = res.data;
                document.getElementById('todayLogs').textContent = stats.total;
                document.getElementById('loginLogs').textContent = stats.operators; // 使用操作人数代替登录次数
                document.getElementById('errorLogs').textContent = stats.failed;
                document.getElementById('totalLogs').textContent = stats.total;
            }
        });
    }
    
    // 页面加载完成后立即更新统计数据
    $(document).ready(function() {
        updateStatsFromAPI();
        
        // 每分钟更新一次统计数据
        setInterval(updateStatsFromAPI, 60000);
    });
    
    // 绑定搜索回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchLogs();
        }
    });
    
    // 监听IP地址输入框
    document.querySelector('input[name="ipFilter"]').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            reloadTable();
        }
    });
    
    console.log('操作日志页面加载完成');
    
    // 修复菜单展开问题
    setTimeout(function() {
        console.log('开始修复菜单...');
        
        // 检查当前页面菜单结构
        $('.layui-nav-tree .layui-nav-item').each(function(i) {
            var $item = $(this);
            var $link = $item.children('a');
            var linkText = $link.text().trim();
            var linkHref = $link.attr('href');
            var hasChild = $item.children('.layui-nav-child, dl').length > 0;
            
            console.log('菜单项' + i + ':', linkText, 'href:', linkHref, '有子菜单:', hasChild);
            
            // 如果是javascript:;链接但没有子菜单，则添加子菜单
            if (linkHref === 'javascript:;' && !hasChild) {
                if (linkText.includes('车辆管理')) {
                    $item.append(`
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/vehicle/list">车辆列表</a></dd>
                            <dd><a href="/admin/vehicle/add">新增车辆</a></dd>
                            <dd><a href="/admin/vehicle/temporary">临时车辆</a></dd>
                        </dl>
                    `);
                    console.log('添加车辆管理子菜单');
                } else if (linkText.includes('缴费管理')) {
                    $item.append(`
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/payment/list">缴费记录</a></dd>
                            <dd><a href="/admin/payment/orders">订单管理</a></dd>
                            <dd><a href="/admin/payment/settings">缴费设置</a></dd>
                        </dl>
                    `);
                    console.log('添加缴费管理子菜单');
                } else if (linkText.includes('设备管理')) {
                    $item.append(`
                        <dl class="layui-nav-child">
                            
                        </dl>
                    `);
                    console.log('添加设备管理子菜单');
                } else if (linkText.includes('统计报表')) {
                    $item.append(`
                        <dl class="layui-nav-child">
                            <dd><a href="/admin/report/income">收入统计</a></dd>
                            <dd><a href="/admin/report/vehicle">车辆统计</a></dd>
    
                        </dl>
                    `);
                    console.log('添加统计报表子菜单');
                }
            }
        });
        
        // 重新绑定菜单点击事件
        // 先解除layui自带的菜单事件
        layui.element.on('nav(nav)', function(){
            return false; // 阻止layui默认事件
        });
        
        // 绑定自定义菜单点击事件
        $('.layui-nav-tree .layui-nav-item > a[href="javascript:;"]').off('click.menufix').on('click.menufix', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var $this = $(this);
            var $item = $this.parent('.layui-nav-item');
            var $children = $item.children('.layui-nav-child');
            var menuText = $this.clone().children().remove().end().text().trim(); // 获取纯文本，排除图标
            
            console.log('菜单点击:', menuText, '子菜单数量:', $children.length);
            
            if ($children.length > 0) {
                if ($item.hasClass('layui-nav-itemed')) {
                    $item.removeClass('layui-nav-itemed');
                    console.log('关闭菜单:', menuText);
                } else {
                    // 先关闭其他展开的菜单
                    $('.layui-nav-tree .layui-nav-item').removeClass('layui-nav-itemed');
                    // 展开当前菜单
                    $item.addClass('layui-nav-itemed');
                    console.log('展开菜单:', menuText);
                }
            }
            
            return false;
        });
        
        console.log('菜单修复完成');
    }, 1000);
});
</script>

{include file="layout/layui_footer" /}